package com.lhb.boyixue.user.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lhb.boyixue.base.JwtUtil;
import com.lhb.boyixue.user.mapper.UserMapper;
import com.lhb.boyixue.user.model.*;
import com.lhb.boyixue.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @author 86131
 * @version 1.0
 * @description 用户服务
 * @date 2025/5/23 上午10:52
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    JwtUtil jwtUtil;
    @Override
    public LoginResult login(LoginRequest loginRequest) {
        RestTemplate restTemplate = new RestTemplate();
        String code=loginRequest.getCode();//授权码
        // GET 请求
        String result = restTemplate.getForObject("https://api.weixin.qq.com/sns/jscode2session?appid=wx2c3d1c1ab4918c0d&secret=d1a5fcaa7c2924bb17b418e171a7f49a&js_code="+code+"&grant_type=authorization_code",String.class);
        // 然后使用Jackson或Gson等工具手动转换
        ObjectMapper mapper = new ObjectMapper();
        WxLoginResult wxResult = null;
        try {
            wxResult = mapper.readValue(result, WxLoginResult.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        String openid = wxResult.getOpenid();

        User user = userMapper.getUserByOpenid(openid);
        if(user ==null){
            userMapper.addUser(openid);
            user=User.builder().openid(openid).build();
        }

      String token=  jwtUtil.generateToken(openid);

        return LoginResult.builder()
                .user(user)
                .token(token)
                .build();
    }

    @Override
    public setGradeAndTimeModel setGradeAndTime(setGradeAndTimeModel setGradeAndTimeModel) {

        int i=userMapper.setGradeAndTime(setGradeAndTimeModel);
        if(i>0){
            return setGradeAndTimeModel;
        }

        return null;
    }
}
